package net.csdn.business.auth.filter;


import cn.authing.core.types.User;
import cn.hutool.core.util.IdUtil;
import net.csdn.business.common.constant.AuthConstants;
import net.csdn.business.common.oauth2.model.LoginUser;
import net.csdn.business.common.utils.AuthUtil;
import net.csdn.business.common.oauth2.component.AuthingAuthenticationToken;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * token过滤器 验证token有效性
 * 
 * @author zhangyal
 */
@Component
public class AuthingAuthenticationTokenFilter extends OncePerRequestFilter
{

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException
    {
        String authingToken= AuthUtil.getIdToken(request);
        if(StringUtils.isNoneBlank(authingToken)){
            User user =null;
            try{
                 //user = authingService.getUserByToken(authingToken);
                user =null;
            }catch (Exception e){

            }
            //设备id,传此参数是为了让同一账号在多个浏览器登录时产生不通的token。
            String deviceId=request.getParameter(AuthConstants.DEVICE_ID);
            if(StringUtils.isEmpty(deviceId)){
                deviceId= IdUtil.simpleUUID();
            }
            if (user != null) {
                LoginUser loginUser=new LoginUser(user.getId(),user.getUsername(),user.getNickname(),user.getEmail(),deviceId,
                        user.getId(), true, true, true,
                        true, AuthorityUtils.NO_AUTHORITIES);
                AuthingAuthenticationToken authenticationToken = new AuthingAuthenticationToken(loginUser,loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        chain.doFilter(request, response);
    }
}
